﻿using System;
using System.Linq;
using System.Web.Mvc;
using Kelper.Domain.Data.Abstract;
using Kelper.ViewModels;
using Kelper.Domain.Models;

namespace Kelper.Controllers
{
    public class AdminController : BaseController
    {
        private IUserRepository users;
        private IRecipeRepository recipes;
        private ICategoryRepository categories;

        public AdminController(IUserRepository userRepo, IRecipeRepository recipeRepo, ICategoryRepository categoryRepo)           
        {
            users = userRepo;
            recipes = recipeRepo;
            categories = categoryRepo;
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!Request.IsLocal)
                filterContext.Result = HttpNotFound();  // Let's pretend it doesn't exist
        }

        public ActionResult Index()
        {
            return View(new AdminViewModel
            {
                Recipes = recipes.Recipes,
                Users = users.Users,
                Categories = categories.Categories
            });
        }

        [HttpPost]
        [ActionName("Add-Category")]
        public RedirectToRouteResult AddCategory(string name)
        {
            if (!String.IsNullOrWhiteSpace(name))
                categories.Add(name);

            return RedirectToAction("Index", "admin");
        }

        [HttpPost]
        [ActionName("Remove-Category")]
        public RedirectToRouteResult RemoveCategory(string id)
        {
            categories.Remove(id);

            return RedirectToAction("Index", "admin");
        }

        [HttpPost]
        [ActionName("Rename-Category")]
        public ActionResult RenameCategory(string oldName, string newName)
        {
            if (!String.IsNullOrWhiteSpace(newName))
                categories.Rename(oldName, newName);

            return RedirectToAction("Index", "admin");
        }

        [HttpPost]
        [ActionName("Remove-User")]
        public RedirectToRouteResult RemoveUser(string id)
        {
            users.Unregister(id);

            return RedirectToAction("Index", "admin");
        }
    }
}
